package test.util;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zhenjie.Ji
 * @description TLV格式数据解析工具类
 * @date 2025/2/20 17:13
 */
public class TlvParseUtils {

    /**
     * 解析TLV格式数据方法
     *
     * @param hexData hexString字符串数据
     * @return 返回TV格式map
     */
    public static Map<String, String> parseTLV(String hexData) {
        Map<String, String> tlvMap = new LinkedHashMap<>();
        int index = 0;
        while (index < hexData.length()) {
            String tag = hexData.substring(index, index + 2);
            index += 2;
            int length = Integer.parseInt(hexData.substring(index, index + 2), 16);
            index += 2;
            String value = hexData.substring(index, index + length * 2);
            index += length * 2;
            tlvMap.put(tag, value);
        }
        return tlvMap;
    }

    /**
     * hexString 字符串转byte数组方法
     *
     * @param hexString hexString 字符串
     * @return 返回byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * 将TLV值转换为UTF-8字符串
     *
     * @param hexValue TLV值
     * @return 返回字符串
     */
    public static String convertHexToString(String hexValue) {
        return new String(hexStringToBytes(hexValue), StandardCharsets.UTF_8);
    }

    public static String byteArrayToHex(byte[] byteArray) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : byteArray) {
            hexString.append(String.format("%02x", b));  // 转换为两位16进制字符串
        }
        return hexString.toString();
    }

}
